import { Card, Empty, Table } from "@arco-design/web-react";
import SearchForm from "./SearchForm";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { getPageInfo } from "@/utils/getPageInfo";
const DEFAULT_QUERY_DATA = {
  pageIndex: 1,
  pageSize: 10,
  timestamp: new Date().getTime(),
};

export default function ProTable(props) {
  const {
    queryKey,
    queryFn,
    operation,
    defaultQueryData = [],
    formOptions,
    tableProps,
    tableRowKey = "id",
    columns,
    emptyText = "暂无数据",
    pagination = {
      showTotal: true,
      totalField: "recordsCount",
      pageField: "page",
      pageSizeField: "pageSize",
    },
  } = props;
  const [queryData, setQueryData] = useState({
    ...DEFAULT_QUERY_DATA,
    ...defaultQueryData,
  }) as any;
  const {
    data: res,
    isLoading,
    isFetching,
  } = useQuery({
    queryKey: [queryKey, queryData],
    queryFn: async () => {
      return queryFn({ ...queryData });
    },
  });

  const loading = isLoading || isFetching;
  return (
    <div>
      <Card bodyStyle={{ paddingBottom: 0 }}>
        <SearchForm 
        initialValues = {defaultQueryData}
        loading = {loading}
        formOptions={formOptions} />
      </Card>
      <Card className="mt-5">
        {!!operation && (
          <div className="flex justify-between mb-5">{operation}</div>
        )}
        <div className="mt-4 rounded">
          <Table
            rowKey={tableRowKey}
            loading={loading}
            columns={columns}
            data={res?.data || []}
            className={"min-h-[500px]"}
            pagination={{
              ...getPageInfo(res, {
                page: queryData.pageIndex,
                pageSize: queryData.pageSize,
                ...pagination,
              }),
              onChange: (pageIndexber, pageSize) => {
                setQueryData({
                  ...queryData,
                  pageIndex: pageIndexber,
                  pageSize: pageSize,
                });
              },
            }}
            scroll={{ x: 1142 }}
            noDataElement={!loading && <Empty description={emptyText} />}
            {...tableProps}
          />
        </div>
      </Card>
    </div>
  );
}
